//
//  HomeTableViewController.m
//  VEW
//
//  Created by lanou3g on 15/7/17.
//  Copyright (c) 2015年 Y团. All rights reserved.
//

#import "HomeTableViewController.h"
#import "HomeModel.h"
#import "HomeTableViewCell.h"
#import "SDCycleScrollView.h"
#import "MJRefresh.h"
#import "DetailViewController.h"
#import "UIImageView+WebCache.h"
#import "AFHTTPRequestOperationManager.h"

#import "AppDelegate.h"

#import "RWDropdownMenu.h"

#import "RightTableViewController.h"


@interface HomeTableViewController()<SDCycleScrollViewDelegate>{
//    NSInteger pageNum;
}



@property(nonatomic,retain)NSMutableArray *dataArray;
//加载更多的数组
@property(nonatomic,retain)NSMutableArray *moreArray;
//刷新用
@property(nonatomic,assign)BOOL isRefresh;
//轮播用
@property(nonatomic,retain)NSMutableArray *strArray;
@property(nonatomic,retain)NSMutableArray *titleArray;
@property(nonatomic,copy) NSString *myUrl;

//@property(nonatomic,retain)NSString *str1,*str2,*str3;

@property (nonatomic, strong) NSArray *menuItems;

@property (nonatomic, assign) RWDropdownMenuStyle menuStyle;


@end


@implementation HomeTableViewController

- (void)viewDidLoad
{
    [super viewDidLoad];


    
    //navigation标题
    UIView *titleView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 100, 30)];
    self.navigationItem.titleView=titleView;

    
    UIImageView *imageTitleView = [[UIImageView alloc] initWithImage: [UIImage imageNamed:@"图标微视界.png"]];

    imageTitleView.frame=CGRectMake(0, 0, 30, 30);
    
    UILabel *titleLabel=[[UILabel alloc]init];
    titleLabel.text=@"微视界";

    titleLabel.frame=CGRectMake(40, 0, 60, 30);

    
    [titleView addSubview:imageTitleView];
    [titleView addSubview:titleLabel];
    
    self.pageNum = 1;
    
    self.dataArray = [NSMutableArray array];
    
    self.moreArray = [NSMutableArray array];
    
    //注册cell
    [self.tableView registerClass:[HomeTableViewCell class] forCellReuseIdentifier:@"home_cell"];
    
    self.myUrl = @"http://api.m.jiemian.com/article/cate/260.json";
    
    [self data];
    [self setHeadImages];
  
    //左右按钮
    
    [self setTopButton];
   
    //调用刷新
    
    [self setupRefresh];

}

- (NSArray *)menuItems
{
//    leftButtonImage=[leftButtonImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    
    if (!_menuItems)
    {
        _menuItems =
        @[
          [RWDropdownMenuItem itemWithText:@"娱乐" image:[UIImage imageNamed:@"右娱乐"] action:nil],
          [RWDropdownMenuItem itemWithText:@"体育" image:[UIImage imageNamed:@"右体育"] action:nil],
          [RWDropdownMenuItem itemWithText:@"科技" image:[UIImage imageNamed:@"右科技"] action:nil],
          [RWDropdownMenuItem itemWithText:@"军事" image:[UIImage imageNamed:@"右军事"] action:nil],
          [RWDropdownMenuItem itemWithText:@"游戏" image:[UIImage imageNamed:@"右游戏"] action:nil],
          [RWDropdownMenuItem itemWithText:@"投资" image:[UIImage imageNamed:@"右投资"] action:nil],
          ];
    }
    return _menuItems;
}



- (void)presentMenuFromNav:(id)sender
{
    RWDropdownMenuCellAlignment alignment = RWDropdownMenuCellAlignmentCenter;
    if (sender == self.navigationItem.rightBarButtonItem)
    {
        alignment = RWDropdownMenuCellAlignmentRight;
    }
//    else
//    {
//        alignment = RWDropdownMenuCellAlignmentRight;
//    }
    [RWDropdownMenu presentFromViewController:self withItems:self.menuItems align:alignment style:self.menuStyle navBarImage:[sender image] completion:nil];
}

- (void)presentMenuInPopover:(id)sender
{
    [RWDropdownMenu presentInPopoverFromBarButtonItem:sender withItems:self.menuItems completion:nil];
}

- (void)presentStyleMenu:(id)sender
{
    NSArray *styleItems =
    @[
      [RWDropdownMenuItem itemWithText:@"Black Gradient" image:nil action:^{
          self.menuStyle = RWDropdownMenuStyleBlackGradient;
      }],
      [RWDropdownMenuItem itemWithText:@"Translucent" image:nil action:^{
          self.menuStyle = RWDropdownMenuStyleTranslucent;
      }],
      ];
    
    [RWDropdownMenu presentFromViewController:self withItems:styleItems align:RWDropdownMenuCellAlignmentCenter style:self.menuStyle navBarImage:nil completion:nil];
}


-(void)setTopButton
{
    UIImage *leftButtonImage=[UIImage imageNamed:@"左按钮"];
    
    leftButtonImage=[leftButtonImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    
    self.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc]initWithImage:leftButtonImage style:UIBarButtonItemStyleDone target:self action:@selector(openOrCloseLeftList)];
    
    
    
    UIImage *rightButtonImage=[UIImage imageNamed:@"右按钮"];
    
    rightButtonImage=[rightButtonImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:rightButtonImage style:UIBarButtonItemStylePlain target:self action:@selector(pushToRight)];
}

-(void)pushToRight
{
    RightTableViewController *rightTVC = [[RightTableViewController alloc]init];
    
    [self.navigationController pushViewController:rightTVC animated:YES];
}

//- (void)presentMenuButtonTapped {
//    // init YALContextMenuTableView tableView
//    if (!self.contextMenuTableView) {
//        self.contextMenuTableView = [[YALContextMenuTableView alloc]initWithTableViewDelegateDataSource:self];
//        self.contextMenuTableView.animationDuration = 0.15;
//        //optional - implement custom YALContextMenuTableView custom protocol
//        self.contextMenuTableView.yalDelegate = self;
//        
//        //register nib
//        UINib *cellNib = [UINib nibWithNibName:@"ContextMenuCell" bundle:nil];
//        [self.contextMenuTableView registerNib:cellNib forCellReuseIdentifier:menuCellIdentifier];
//    }
//    
//    // it is better to use this method only for proper animation
//    [self.contextMenuTableView showInView:self.navigationController.view withEdgeInsets:UIEdgeInsetsZero animated:YES];
//}





//左抽屉
- (void)openOrCloseLeftList
{
    AppDelegate *tempAppDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    
    if (tempAppDelegate.LeftSlideVC.closed)
    {
        [tempAppDelegate.LeftSlideVC openLeftView];
    }
    else
    {
        [tempAppDelegate.LeftSlideVC closeLeftView];
    }
}

-(void)setHeadImages
{
    UIView *headView=[[UIView alloc]initWithFrame:CGRectMake(0,0,self.view.frame.size.width, self.view.frame.size.width*0.6)];
    self.tableView.tableHeaderView=headView;
    
    // 情景：采用网络图片实现
  
    NSArray *imagesURLStrings= _strArray;
    
    // 情景：图片配文字
    NSArray *titles = _titleArray;
    
    
    CGFloat w = self.view.bounds.size.width;
    
    //网络加载 --- 创建带标题的图片轮播器
    SDCycleScrollView *cycleScrollView2 = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, w, w*0.6) imageURLStringsGroup:nil]; // 模拟网络延时情景
    cycleScrollView2.pageControlAliment = SDCycleScrollViewPageContolAlimentRight;
    cycleScrollView2.delegate = self;
    cycleScrollView2.titlesGroup = titles;
    cycleScrollView2.dotColor = [UIColor whiteColor]; // 自定义分页控件小圆标颜色
    cycleScrollView2.placeholderImage = [UIImage imageNamed:@"place.jpg"];
    [self.view addSubview:cycleScrollView2];
    
    //             --- 模拟加载延迟
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        cycleScrollView2.imageURLStringsGroup = imagesURLStrings;
    });

}


//解析数据
-(void)data{
    // 网络请求
    AFHTTPRequestOperationManager * manager= [AFHTTPRequestOperationManager manager];
    NSString *url = [self.myUrl stringByAppendingString:[NSString stringWithFormat:@"?&page=%ld",self.pageNum]];
    [manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (!self.isRefresh) {
            [self.dataArray removeAllObjects];
        }
        
        NSDictionary *dic = responseObject[@"result"];
        NSArray * array = dic[@"rst"];
        
        self.strArray=[NSMutableArray array];
        self.titleArray=[NSMutableArray array];
        int num=0;
        for (NSDictionary *Bdic in array) {
            num++;
            HomeModel * home = [HomeModel new];
            home.title = Bdic[@"title"];
            home.publishtime = Bdic[@"publishtime"];
            home.MyID=Bdic[@"id"];
            home.z_image = Bdic[@"z_image"];
            NSArray * a = Bdic[@"author_list"];
            NSDictionary * d = [a lastObject];
            home.name = d[@"name"];
            
            if (num<=4) {
                [_strArray addObject:Bdic[@"l_image"]];
                [_titleArray addObject:Bdic[@"title"]];
                [self.moreArray addObject:home];
            }
            if (num>4) {
                [self.dataArray addObject:home];
            }
        }
        [self setHeadImages];
        [self.tableView reloadData];
    }failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    }];
}

#pragma mark - 刷新实现 -

// 刷新
-(void)setupRefresh {
    //下拉刷新
    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    
    [self.tableView headerBeginRefreshing];
    
    //上拉加载跟多(进入刷新状态就会调用self的footerRefreshing)
    
    [self.tableView addFooterWithTarget:self action:@selector(footerRereshing)];
}
// ------下拉刷新
- (void)headerRereshing
{
    [self.tableView headerEndRefreshing];
    self.isRefresh = NO;
    [self data];
//    [self setHeadImages];
    [self.tableView reloadData];

}

// ------上拉加载
- (void)footerRereshing
{
    _pageNum++;
    
    self.isRefresh = YES;
    [self data];
    
    [self.tableView footerEndRefreshing];
}


#pragma mark - Table view data source -

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    // Return the number of rows in the section.
    return self.dataArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HomeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"home_cell" forIndexPath:indexPath];
    HomeModel *home = [self.dataArray objectAtIndex:indexPath.row];
    cell.titleLabel.text = home.title;
   
    cell.nameLabel.text = home.name;
    
    
    
    
    //把秒数转化成yyyy-MM-dd hh:mm:ss格式
    NSDate *dd = [NSDate dateWithTimeIntervalSince1970:[home.publishtime intValue]];

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"MM/dd HH:mm:ss"];
    NSString *showtimeNew = [formatter stringFromDate:dd];

    
    cell.publishLabel.text=showtimeNew;
    
    
    cell.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
    //文本框自适应文本
    CGSize size = [cell.titleLabel sizeThatFits:CGSizeMake(cell.titleLabel.frame.size.width, MAXFLOAT)];
    cell.titleLabel.frame = CGRectMake(cell.titleLabel.frame.origin.x, cell.titleLabel.frame.origin.y, cell.titleLabel.frame.size.width, size.height);
    //作者label自适应
    CGSize size1 = [cell.nameLabel sizeThatFits:CGSizeMake(cell.nameLabel.frame.size.width, MAXFLOAT)];
    cell.nameLabel.frame = CGRectMake(cell.nameLabel.frame.origin.x, cell.nameLabel.frame.origin.y, size1.width, size1.height);
    //发布label自适应
    CGSize size2 = [cell.publishLabel sizeThatFits:CGSizeMake(cell.publishLabel.frame.size.width, MAXFLOAT)];
    cell.publishLabel.frame = CGRectMake(cell.publishLabel.frame.origin.x, cell.publishLabel.frame.origin.y, size2.width, size2.height);
    
    NSURL *url = [NSURL URLWithString:home.z_image];
    [cell.z_image sd_setImageWithURL:url];
    
    
    return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 160;
}
//点击事件
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
    DetailViewController *detailVC = [[DetailViewController alloc]init];
    
    HomeModel *home = [[HomeModel alloc]init];
    
    home = self.moreArray[index];
    
    detailVC.homeData = home;
    
    [self.navigationController pushViewController:detailVC animated:YES];
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    DetailViewController *detailVC = [[DetailViewController alloc]init];
    
    HomeModel *home = [[HomeModel alloc]init];
    
    home = self.dataArray[indexPath.row];
    
    detailVC.homeData = home;
    
    detailVC.hidesBottomBarWhenPushed=YES;
    
    [self.navigationController pushViewController:detailVC animated:YES];
}

@end
